package tripx.sql;

import java.util.ArrayList;

import tripx.system.Logger;
import tripx.util.StringHelper;

/**
 * In fact, it does nothing, only encapsulate the predefined sql.
 * 
 * @author zhb
 * 
 */
public class SqlHandler {

	private ArrayList<SqlAction> queryActionList;

	private int status;

	public SqlHandler(ArrayList<SqlAction> queryActionList) {
		this.queryActionList = queryActionList;
	}

	/**
	 * get the predefined sql. If the actionKey does not map any sql, then null
	 * will be returned. of course, if there is any error happened, the status
	 * signal will be 0.
	 * 
	 * @param actionKey
	 * @param params
	 * @return
	 */
	public String getSql(String actionKey, String... params) {
		Logger logger = Logger.getInstance();
		SqlAction targetAction = null;
		String sql = null;
		for (SqlAction action : queryActionList) {
			if (action.getActionKey().equals(actionKey)) {
				targetAction = action;
				break;
			}
		}
		if (targetAction == null) {
			// the target query action not found
			status = 0;
			logger.err("target action is null, actionKey = " + actionKey);
		} else if (targetAction.getParamCount() != params.length) {
			status = 0;
			logger.err("Param Count Doesn not Match, expect "
					+ targetAction.getParamCount() + ", but " + params.length);
		} else {
			// replace the place holder value
			sql = targetAction.getActionSql();
			// trick replacement
			String[] tricks = sql.split("\\?");
			sql = "";
			for (int i = 0; i < params.length; i++) {
				// if the parameter is a number.
				try {
					Double.parseDouble(params[i]);
					sql += (tricks[i] + params[i]);
				} catch (NumberFormatException e) {
					sql += (tricks[i] + '"' + StringHelper.strip(params[i]) + '"');
				}
			}
			if (tricks.length > params.length) {
				sql += tricks[tricks.length - 1];
			}
			// trick replacement ends
			status = 1;
		}
		return sql;
	}

	/**
	 * get the latest status of this object's operation
	 * 
	 * @return 1--Not Error. 0--Error Happened
	 */
	public int getStatus() {
		return status;
	}
}
